<?php

class User_model extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }

    public function insert($user_info)
    {
        $data = array('openid' => $user_info['openid'],
                      // 'nickname' => $user_info['nickname'],
                      // 'sex' => $user_info['sex'],
                      // 'province' => $user_info['province'],
                      // 'city' => $user_info['city'],
                      // 'country' => $user_info['country'],
                      // 'headimgurl' => $user_info['headimgurl'],
                      );

        // if ($data['headimgurl']) {
        //     $data['headimgurl'] = $data['headimgurl'] = substr($data['headimgurl'], 0, strlen($data['headimgurl'])-1);
        // }

        $this->db->insert('user', $data);
    }

    public function get_user_by_openid($openid)
    {
        $this->db->where('openid', $openid);
        $query = $this->db->get('user');
        return $query->row();
    }

    public function set_top_level($openid, $level)
    {
        $this->db->set('top_level', $level);
        $this->db->where('openid', $openid);
        $this->db->update('user');
    }

    public function set_life($openid, $life)
    {
        $this->db->set('life', $life);
        $this->db->where('openid', $openid);
        $this->db->update('user');
    }

    public function set_gift_code($openid, $code)
    {
        $this->db->set('gift_code', $code);
        $this->db->where('openid', $openid);
        $this->db->update('user');
    }

    public function get_rank($level)
    {

        $this->db->where('top_level > ', $level);
        $this->db->order_by('top_level');
        // $query = $this->db->get('user');

        return $this->db->count_all_results('user')+1;
    }

    public function check_top_chance($uid)
    {
        $query = $this->db->get_where('user_info', array('uid'=>$uid), 1);
        return $query->row();
    }
}
